#!/bin/bash
cd "$(dirname "$0")"

die() {
  echo >&2 $1
  exit 1
}

usage() {
  echo >&2 "Usage: $0 id"
  exit 2
}

download_single() {
  local id=$1
  echo "Getting $id"
  if [ -d "libs/$id" ]; then
    die "  --> Downloaded before. Remove it to download again."
  fi

  if [ ! -f "db/$1.url" ]; then
    die "Invalid ID, maybe the library was fetched in an older version or added manually?"
  fi

  local url="$(cat "db/$1.url")"
  echo "  -> Location: $url"
  local tmp=`mktemp -d`
  echo "  -> Downloading package"
  wget "$url" 2>/dev/null -O $tmp/pkg.deb || die "Failed to download package from $url"
  echo "  -> Extracting package"

  pushd $tmp 1>/dev/null
  ar x pkg.deb || die "ar failed"
  tar xf data.tar.* || die "tar failed"
  popd 1>/dev/null

  mkdir libs/$id
  cp $tmp/lib/*/* libs/$id 2>/dev/null || cp $tmp/lib32/* libs/$id 2>/dev/null \
    || die "Failed to save. Check it manually $tmp"
  echo "  -> Package saved to libs/$id"

  rm -rf $tmp
}

if [[ $# != 1 ]]; then
  usage
fi
download_single "$1"
